package com.moefor.clover.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.moefor.clover.dao.BaseDao;

public class BaseDaoImpl<T> implements BaseDao<T>{
	
	@Resource
	private SessionFactory sessionFactory;
	
	private final Class<T> entityClass;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImpl(){
		Type params = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		entityClass = (Class<T>) params;
	}

	@Override
	public Session getSession() {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public T get(Serializable id) {
		// TODO Auto-generated method stub
		return getSession().get(entityClass, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(int id) {
		// TODO Auto-generated method stub
		Query q = getSession().createQuery("FROM " + entityClass.getName() +" e WHERE e.id=?");
		q.setInteger(0, id);
		return (T)q.uniqueResult();
	}

	@Override
	public boolean add(T obj) {
		// TODO Auto-generated method stub
		try {
			getSession().save(obj);
			getSession().flush();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean update(T obj) {
		// TODO Auto-generated method stub
		try {
			getSession().update(obj);
			getSession().flush();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean delete(T obj) {
		// TODO Auto-generated method stub
		try {
			getSession().delete(obj);
			getSession().flush();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean delete(int id) {
		// TODO Auto-generated method stub
		Query q = getSession().createQuery("DELET " + entityClass.getName() +" e WHERE e.id=?");
		q.setInteger(1, id);
		try {
			if(q.executeUpdate()<1){
				return false;
			}else return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}	
}
